﻿using System;//
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Citi.SecurityHelper;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Citi.BOExtraction;

namespace Citi.Encryption
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //using (var client = new PearlBO.SessionPortClient())
            //{
            //    var oCon = new Connection("http://boserver:port/dswsbobje/services/session");
            //    Session m_session = new Session(oCon);

            //    EnterpriseCredential oEnterpriseCredential = new EnterpriseCredential();
            //    oEnterpriseCredential.Login = "John";
            //    oEnterpriseCredential.Password = "MyPassword1973";
            //    oEnterpriseCredential.Locale = "en_US";
            //    oEnterpriseCredential.TimeZone = "GMT+01:00";

            //    SessionInfo oSessionInfo = m_session.Login(oEnterpriseCredential);
            //}

            //using (var client = new PearlBO.SessionPortClient())
            //{
            //    var credential = new PearlBO.EnterpriseCredential
            //    {
            //        Login = "FC16291",
            //        Password = "Dexter010",
            //        Domain = "lac",
            //        Domain = "plboprg.wlb2.nam.nsroot.net:14620",
            //        AuthType = "SSO"
            //    };
            //    var session = client.getServerInfo();


            //    client.login(null, client.getVersion());
            //}

            //return;
            var hrUrl = ("https://hronline.brazil.citigroup.net/siteminderagent/forms/login.fcc");
            var p2pUrl = "https://signon.p2p.citigroup.net/";
            var i7UatUrl = "https://uat.brazilweb.br.citicorp.com/siteminderagent/forms/login.fcc?TYPE=33554433&REALMOID=06-3f395aef-bd9c-0006-0000-534600005346&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-d2MymqAkcJRTP8thRFmJWpl41jCQfYTR%2fi8pnlogZGruwMl8S1FUuyGVwJyyNylejod1uUPjavbLoz1HKPzHs2NfAVcAVjKZ&TARGET=-SM-%2fAPPSL%2fi7%2fconfiguracao%2easpx%2fsistema";
            var gdwUrl = "https://gdw-wfr.nam.nsroot.net/wfrbo/AnalyticalReporting/WebiView.do?bypassLatestInstance=true&cafWebSesInit=true&appKind=InfoView&service=/InfoViewApp/common/appService.do&loc=en&pvl=en_US&ctx=standalone&actId=468&objIds=921989&containerId=28146&pref=maxOpageU%3D50%3BmaxOpageUt%3D200%3BmaxOpageC%3D10%3Btz%3DAmerica%2FNew_York%3BmUnit%3Dinch%3BshowFilters%3Dtrue%3BsmtpFrom%3Dtrue%3BpromptForUnsavedData%3Dtrue%3B";
            var pearlUrl = "https://pearl.nj.ssmb.com/siteminderagent/forms/login.fcc?TYPE=33554433&REALMOID=06-fb51622c-add9-1001-9bdc-847a5366ff21&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-TSXzCZBCWQfzzR6LEV6XtEMrota02ItSl0QgFPxXin03Wt9NJusCYSasBcT6zdoJT%2fuU6B%2b%2b02sSh2OVblMd8gXfnNQ9TyP9&TARGET=-SM-%2fpsp%2fplpfprg%2fEMPLOYEE%2fEPM%2fc%2fBCC_REPORTS_HOME%2eBCC_BO_R3_LINK%2eGBL%3fFolderPath%3dPORTAL_ROOT_OBJECT%2eBCC_COUNTRY_CORE%2eBCC_REPORTING%2eBCC_BO_R3_LINK_GBL%26IsFolder%3dfalse%26IgnoreParamTempl%3dFolderPath-%2cIsFolder";

            var url = pearlUrl;
            //url = "https://pearl.nj.ssmb.com/psp/plpfprg/EMPLOYEE/EPM/s/WEBLIB_PTPP_SC.HOMEPAGE.FieldFormula.IScript_AppHP?pt_fname=BCC_COUNTRY_CORE&FolderPath=PORTAL_ROOT_OBJECT.BCC_COUNTRY_CORE&IsFolder=true";
            //url = "https://pearl.nj.ssmb.com/psc/plpfprg/EMPLOYEE/EPM/s/WEBLIB_PTPP_SC.HOMEPAGE.FieldFormula.IScript_AppHP?scname=BCC_COUNTRY_CORE&secondary=true&fname=BCC_REPORTING&pt_fname=BCC_REPORTING&PortalCacheContent=true&PSCache-Control=role%2cmax-age%3d60&FolderPath=PORTAL_ROOT_OBJECT.BCC_COUNTRY_CORE.BCC_REPORTING&IsFolder=true";
            //url = "http://plboprg.wlb2.nam.nsroot.net:14620/bobjpsenterprise/jsp/ContextualAwareness/initURE.jsp?infoview=http://plboprg.wlb2.nam.nsroot.net:14620/PartnerPlatformService/service/app/logon.object&vendor=PeopleSoft&cms=corpbo126p.nam.nsroot.net:14670&auth=secpsenterprise&domain=PLPFPRG&token=AAAAqAECAwQAAQAAAAACvAAAAAAAAAAsAARTaGRyAgBOdQgAOAAuADEAMBRI5t1/PBZ6D7YofAnzOlcW4F2AdwAAAGgABVNkYXRhXHicHYtLDkBAEAVrEEsr1yCGFqx9ZiMycQGncDuH8+ikqpN+r4HbJWmGQ5M8nwt2FgxPJ6aclYNQMhO4iEojmzgJRkujklFpd7IefvfUwmTPKA/KTZev9QK0pQwb";
            //browser.LogSingleSignOn("ND61955", SecurityHelper.LoginType.Sso, "https://procure2pay.citigroup.net/");

            var axbrowser = (SHDocVw.WebBrowser_V1)browser.ActiveXInstance;
            axbrowser.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(Web_V1_NewWindow);
            browser.Navigated += new WebBrowserNavigatedEventHandler(browser_Navigated);
            browser.LogSingleSignOn("LD41319", SecurityHelper.LoginType.Sso, url);



        }

        void browser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            //"http://plboprg.wlb2.nam.nsroot.net:14620/InfoViewApp/listing/main.do?appKind=InfoView&service=%2FInfoViewApp%2Fcommon%2FappService.do&initialFolderId=-1"//
            if (e.Url.OriginalString.Contains("appKind=InfoView&service=%2FInfoViewApp%2Fcommon%2FappService.do&initialFolderId=-1"))
            {
                //browser.Navigated -= browser_Navigated;
                //browser.Navigate(e.Url.OriginalString);
                //browser.DocumentCompleted += MainScreenDocumentCompleted;
                browser.DocumentCompleted += InboxDocumentCompleted;
            }
        }

        private void Web_V1_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
        {
            Processed = true;
            browser.Navigate(URL);
        }

        int documentStep = 0;

        private void InboxDocumentCompleted(object sender, EventArgs e)
        {
            var frame = GetWorkspaceBodyFrame((WebBrowser)sender);

            if (frame == null) return;

            var tableReports = frame.Document.GetElementById("ListingURE_listMainTable");

            if (tableReports == null) return;

            var tbody = tableReports.Children.Cast<HtmlElement>().FirstOrDefault(x => x.TagName.ToUpper() == "TBODY");

            if (tbody == null) return;

            documentStep++;
            if (documentStep < 6) return;

            browser.DocumentCompleted -= InboxDocumentCompleted;
            var reports = GetReports(tbody.Children.Cast<HtmlElement>());

            var myHidden = tableReports.Document.GetElementById(string.Format("ListingURE_doubleClickAction{0}", reports.Count() - 1));
            var val = myHidden.GetAttribute("value");
            val = val.Substring("javascript:".Length);
            val = val.Replace("cafAction", "invokeAction");
            frame.Document.InvokeScript("eval", new string[] { val });
        }

        private IEnumerable<Report> GetReports(IEnumerable<HtmlElement> trs)
        {
            var reports = new List<Report>();

            foreach (var tr in trs)
            {
                reports.Add(new Report
                {
                    ElementClick = tr.Children[0],
                    Sent = DateTime.Parse(tr.Children[3].Children[0].GetAttribute("title")),
                    Title = tr.Children[2].Children[0].InnerText
                });
            }

            return reports.OrderByDescending(x => x.Sent);
        }

        private HtmlWindow GetWorkspaceBodyFrame(WebBrowser browser)
        {
            var frame = browser.Document.Window.Frames["headerPlusFrame"];

            frame = frame.Frames.Cast<HtmlWindow>().FirstOrDefault(x => x.Name == "dataFrame");
            if (frame == null) return null;

            frame = frame.Frames.Cast<HtmlWindow>().FirstOrDefault(x => x.Name == "workspaceFrame");
            if (frame == null) return null;

            return frame.Frames.Cast<HtmlWindow>().FirstOrDefault(x => x.Name == "workspaceBodyFrame");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Teste");
        }
    }

    
}
